<template>
  <div>
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="">
        <el-input v-model="searchForm.name" placeholder="作业单状态" clearable />
      </el-form-item>
      <el-form-item label="">
        <el-input v-model="searchForm.state" placeholder="入库单ID" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" round @click="search">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 导出按钮 -->
    <el-button type="warning" round @click="handleExport">导出数据</el-button>
    <div style="height: 20px;"></div>

    <!-- 数据展示区域 -->
    <el-table :data="tableData.resultList" border style="width: 100%" max-height="500">
      <el-table-column prop="inId" sortable label="入库订单序号">
        <template #default="scope">
          <span :class="{ 'unassigned-text': !scope.row.inId }">
            {{ scope.row.inId || '未分配' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="exeWorkerName" sortable label="执行人">
        <template #default="scope">
          <span :class="{ 'unassigned-text': !scope.row.exeWorkerName }">
            {{ scope.row.exeWorkerName || '未分配' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="loadName" sortable label="装卸点">
        <template #default="scope">
          <span :class="{ 'unassigned-text': !scope.row.loadName }">
            {{ scope.row.loadName || '未分配' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="exePlanTime" sortable label="计划时间">
        <template #default="scope">
          <span :class="{ 'unassigned-text': !scope.row.exePlanTime }">
            {{ scope.row.exePlanTime || '未分配' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="exeTime" sortable label="完成时间">
        <template #default="scope">
          <span :class="{ 'unassigned-text': !scope.row.exeTime }">
            {{ scope.row.exeTime || '未分配' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="status" sortable label="作业单状态">
        <template #default="scope">
          <el-tag
            :type="getStatusType(scope.row.status)"
            effect="plain"
          >
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" sortable label="创建时间" />
      <el-table-column prop="createName" sortable label="创建人" />
      <el-table-column prop="updateTime" sortable label="修改时间" />
      <el-table-column prop="updateName" sortable label="修改人" />

      <!-- 操作列 -->
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
          <template v-if="scope.row.status !== '2'">
            <el-button type="primary" size="small" @click="handleAssign(scope.row)">分配</el-button>
            <el-button type="success" size="small" @click="handleStart(scope.row)">开始作业</el-button>
            <el-button size="small" @click="handleComplete(scope.row)">完成作业</el-button>
          </template>
          <el-button type="info" size="small" @click="handleDelete(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分配对话框 -->
    <el-dialog v-model="assignDialogVisible" title="分配作业" width="600">
      <el-form :model="assignForm">
        <el-form-item label="计划执行时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="assignForm.exePlanTime"
            type="datetime"
            placeholder="选择计划执行时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="执行时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="assignForm.exeTime"
            type="datetime"
            placeholder="选择执行时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="执行人" :label-width="formLabelWidth">
          <el-select v-model="assignForm.exeWorkerName" placeholder="请选择执行人">
            <el-option
              v-for="item in employeeOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="装卸点" :label-width="formLabelWidth">
          <el-select v-model="assignForm.loadName" placeholder="请选择装卸点">
            <el-option
              v-for="item in positionOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        
        <!-- 商品列表 -->
        <el-form-item label="商品信息" :label-width="formLabelWidth">
          <div v-for="(item, index) in assignForm.goodsList" :key="index">
            <el-row :gutter="10" style="margin-bottom: 10px;">
              <el-col :span="7">
                <el-input v-model="item.goodsName" placeholder="商品名称" />
              </el-col>
              <el-col :span="7">
                <el-input v-model="item.goodsCount" placeholder="数量" type="number" />
              </el-col>
              <el-col :span="7">
                <el-select v-model="item.shelfName" placeholder="请选择货架">
                  <el-option
                    v-for="shelf in shelfOptions"
                    :key="shelf"
                    :label="shelf"
                    :value="shelf"
                  />
                </el-select>
              </el-col>
              <el-col :span="3">
                <el-button type="danger" @click="removeGoodsItem(index)">删除</el-button>
              </el-col>
            </el-row>
          </div>
          <el-button type="primary" @click="addGoodsItem">添加商品</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAssignConfirm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="作业单详情" width="800">
      <!-- 基本信息 -->
      <div class="detail-section">
        <h3>基本信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="入库订单序号">{{ detailData.inId }}</el-descriptions-item>
          <el-descriptions-item label="执行人">{{ detailData.exeWorkerName }}</el-descriptions-item>
          <el-descriptions-item label="装卸点">{{ detailData.loadName }}</el-descriptions-item>
          <el-descriptions-item label="计划时间">{{ detailData.exePlanTime }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{ detailData.exeTime }}</el-descriptions-item>
          <el-descriptions-item label="作业单状态">{{ detailData.state === '1' ? '启用' : '未开始' }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 商品列表 -->
      <div class="detail-section">
        <h3>商品信息</h3>
        <el-table :data="goodsList" border style="width: 100%">
          <el-table-column prop="goodsName" label="商品名称" />
          <el-table-column prop="goodsCount" label="数量" />
          <el-table-column prop="shelfName" label="货架号" />
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分页区域 -->
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="searchCondition.pageNum"
        v-model:page-size="searchCondition.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.totalNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { searchShelfName,searchEmployeeName,searchPositioName, searchInStoreGoods,searchInOperation, updateInOperation ,searchInOperationGoods,updateInOperationStatus} from '../api/api.js'

// ==============================

// 表格数据对象
const tableData = ref(
 [], // 当前页数据列表
)

// 对话框显示状态
const assignDialogVisible = ref(false) // 指派对话框
const formLabelWidth = '120px'         // 表单标签宽度

// 搜索表单数据
const searchForm = reactive({
  inId: '',
  status: ''
})

// 指派表单数据
const assignForm = reactive({
  id: '',
  exePlanTime: '',
  exeTime: '',
  exeWorkerName: '',
  loadName: '',
  inId: '',
  goodsList: []  // 添加商品列表
})

const searchCondition = {
  inId: '',
  status: '',
  pageNum: 1,      
  pageSize: 10     
}

// 详情对话框显示状态
const detailDialogVisible = ref(false)

// 详情数据
const detailData = reactive({
  inId: '',
  exeWorkerName: '',
  loadName: '',
  exePlanTime: '',
  exeTime: '',
  state: ''
})

// 商品列表数据
const goodsList = ref([])

// 添加选项数据
const employeeOptions = ref([])
const positionOptions = ref([])
const shelfOptions = ref([])

// 获取选项数据的方法
const loadOptions = async () => {
  try {
    // 获取执行人列表
    const employeeRes = await searchEmployeeName()
    if (employeeRes.data && employeeRes.data.data) {
      employeeOptions.value = employeeRes.data.data
    }
    
    // 获取装卸点列表
    const positionRes = await searchPositioName()
    if (positionRes.data && positionRes.data.data) {
      positionOptions.value = positionRes.data.data
    }
    
    // 获取货架列表
    const shelfRes = await searchShelfName()
    if (shelfRes.data && shelfRes.data.data) {
      // console.log(shelfRes.data.data)
      // 只过滤type为2的货架
      shelfOptions.value = shelfRes.data.data
        .filter(shelf => shelf.type === '2')
        .map(shelf => shelf.shelfName)
    }
  } catch (error) {
    console.error('加载选项数据失败:', error)
    ElMessage.error('加载选项数据失败')
  }
}

// ==============================



/**
 * 查询列表
 */
 const search = async () => {
  try {
    searchCondition.inId = searchForm.inId
    searchCondition.status = searchForm.status
    const res = await searchInOperation(searchCondition)
    
    if (res.data && res.data.data) {
      tableData.value = res.data.data
      ElMessage.success('查询成功')
      console.log(tableData.value)
    } else {
      ElMessage.warning('未获取到数据')
      tableData.value = { resultList: [], totalNum: 0 } // 设置空数据
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败: ' + (error.message || '未知错误'))
    tableData.value = { resultList: [], totalNum: 0 } // 发生错误时设置空数据
  }
}

/**
 * 分配按钮点击事件
 */
const handleAssign = async (row) => {
  try {
    await loadOptions() // 加载选项数据
    // 尝试获取商品列表
    const res = await searchInStoreGoods(parseInt(row.inId))
    if (res.data && res.data.data) {
      goodsList.value = res.data.data
    } else {
      goodsList.value = [] // 如果没有数据则显示空列表
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    goodsList.value = [] // 发生错误时显示空列表
    ElMessage.warning('获取商品列表失败')
  }
  // console.log(goodsList.value)
  console.log(employeeOptions.value)
  console.log(shelfOptions.value)

  assignForm.id = row.id
  assignForm.exePlanTime = row.exePlanTime
  assignForm.exeTime = row.exeTime
  assignForm.exeWorkerName = row.exeWorkerName
  assignForm.loadName = row.loadName
  assignForm.inId = row.inId
  assignForm.goodsList = goodsList.value || [{
    goodsName: '',
    goodsCount: 1,
    shelfName: ''
  }]

  
  assignDialogVisible.value = true
}

/**
 * 分配确认事件
 */
const handleAssignConfirm = async () => {
  try {
    console.log(assignForm)
    await updateInOperation(assignForm)
    ElMessage.success('分配成功')
    search()
    assignDialogVisible.value = false
  } catch (error) {
    ElMessage.error('分配失败')
  }
}

/**
 * 删除
 */
const handleDelete = async (row) => {
  // 保存基本信息
  Object.assign(detailData, row)
  console.log(detailData)
  
  try {
    // 获取商品列表
    const res = await searchInOperationGoods(row.id)
    goodsList.value = res.data.data
    // 显示详情对话框
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取详情失败')
  }
}

/**
 * 改变每页显示数量
 */
const handleSizeChange = (val) => {
  
  search()
}

/**
 * 改变当前页码
 */
const handleCurrentChange = (val) => {

  search()
}

//更新状态
const toggleStatus = (row) => {
  row.state = row.state === '1' ? '0' : '1'
  updatePosition(row).then(() => {
    search()
  })
}

/**
 * 导出数据
 */
const handleExport = () => {
  // 导出逻辑
}

/**
 * 添加商品项
 */
const addGoodsItem = () => {
  assignForm.goodsList.push({
    goodsName: '',
    goodsCount: 1,
    shelfName: ''
  })
}

/**
 * 删除商品项
 */
const removeGoodsItem = (index) => {
  assignForm.goodsList.splice(index, 1)
}

/**
 * 获取状态文本
 */
const getStatusText = (status) => {
  switch (status) {
    case '0':
      return '未开始'
    case '1':
      return '执行中'
    case '2':
      return '已完成'
    default:
      return '未知状态'
  }
}

/**
 * 获取状态标签类型
 */
const getStatusType = (status) => {
  switch (status) {
    case '0':
      return 'info'     // 未开始 - 灰色
    case '1':
      return 'primary'  // 执行中 - 蓝色
    case '2':
      return 'success'  // 已完成 - 绿色
    default:
      return ''
  }
}

/**
 * 开始作业
 */
const handleStart = async (row) => {
  console.log(row)

  try {
    await updateInOperationStatus({
      inId: row.inId,
      status: '1'  // 设置状态为执行中
    })
    // 本地更新状态
    const targetRow = tableData.value.resultList.find(item => item.id === row.id)
    if (targetRow) {
      targetRow.status = '1'
    }
    ElMessage.success('开始作业成功')
  } catch (error) {
    ElMessage.error('开始作业失败')
  }
}

/**
 * 完成作业
 */
const handleComplete = async (row) => {
  try {
    await updateInOperationStatus({
      inId: row.inId,
      status: '2'  // 设置状态为已完成
    })
    // 本地更新状态
    const targetRow = tableData.value.resultList.find(item => item.id === row.id)
    if (targetRow) {
      targetRow.status = '2'
    }
    // ElMessage.success('完成作业成功')
  } catch (error) {
    ElMessage.error('完成作业失败')
  }
  search()

}

onMounted(() => {
  search()
})
</script>

<style scoped>
 .demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.operation-area {
  margin: 15px 0;
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}

.unassigned-text {
  color: #909399;
  opacity: 0.7;
}

.el-row {
  margin-bottom: 10px;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h3 {
  margin-bottom: 15px;
  font-weight: bold;
}
</style>
